<template>
    <div class="stu-product">

        <!-- 搜索 -->
        <div class="search">
            <el-select
                       v-model="searchInputValue"
                       reserve-keyword
                       filterable
                       clearable
                       remote
                       :zIndex="999"
                       placeholder="输入姓名进行搜索"
                       :remote-method="remoteMethod"
                       @change='handleSelectSearchKey'
                       :loading="false">
                <el-option
                           v-for="item in options"
                           :key="item._id"
                           :value="item.name" />
            </el-select>
            <el-button :icon="Search" type="primary" @click="handleSearchButton">搜索</el-button>
        </div>
        <!-- 添加按钮 -->
        <el-button type="primary" :icon="Plus" @click="handleAddStu" v-has:add="permissionButton">添加</el-button>

        <!-- 导出excel -->
        <el-button @click="handleExportExcel">
            <svg class="icon" aria-hidden="true">
                <use xlink:href="#icon-Excel"></use>
            </svg>
            <span>导出excel</span>
        </el-button>

        <!-- 表格数据部分 -->
        <el-table :data="stuTableData" border style="width: 100%" v-loading="tableLoading">
            <el-table-column align="center" label="头像">
                <template #default="scope">
                    <el-image
                              style="width: 100px; height: 50px"
                              :src="scope.row.headimgurl"
                              :zoom-rate="1.2"
                              :preview-src-list="srcList"
                              :initial-index="scope.$index"
                              fit="cover" />
                </template>
            </el-table-column>
            <el-table-column align="center" prop="name" label="姓名"></el-table-column>
            <el-table-column align="center" prop="degree" label="学历"></el-table-column>
            <el-table-column align="center" prop="class" label="班级"></el-table-column>
            <el-table-column align="center" prop="productUrl" label="项目"></el-table-column>
            <el-table-column align="center" prop="cTime" label="创建时间"></el-table-column>
            <el-table-column align="center" label="操作">
                <template #default="scope">
                    <el-button type="primary" v-has:read="permissionButton" :icon="View" circle />
                    <el-button type="primary" v-has:edit="permissionButton" @click="handleEditStu(scope.row, scope)"
                               :icon="Edit" circle />
                    <el-button type="danger" v-has:delete="permissionButton" @click="handleDelete(scope.row)"
                               :icon="Delete" circle />
                </template>
            </el-table-column>

        </el-table>

        <!-- 分页器 -->
        <el-pagination background layout="prev, pager, next" :page-size="5" @current-change="handleSizeChange"
                       v-model:current-page='currentPage'
                       :total="pageTotal" />
    </div>
    <stuDialog :title="dialogTitle" :actionType="actionType" :getlistFn="getStuList" :reDisplayData="reDisplayData">
    </stuDialog>
</template>
<script setup>
import { ref } from "vue"
import { Plus } from '@element-plus/icons-vue'
//引入发送请求的方式
import * as api from "@/api/stu"
//引入el图标
import {
    Warning,
    Delete,
    Edit,
    View,
    Search,
} from '@element-plus/icons-vue'
import stuDialog from "@/components/Dialog/index.vue"
//引入pinia仓库
import useStuDialog from "@/store/stuDialog"
//引入提示反馈
import { ElMessage, ElMessageBox } from "element-plus"
//引入导出数据的库
import qee from "qf-export-excel"
//引入store
import useUsers from "@/store/users"

let userStore = useUsers();

//声明自定义指令,用于控制按钮级的权限

//1.获取用户的权限数据,一般从uerInfo中获取

let permissionButton = userStore.permission

console.log(userStore.permission)

//2.创建一个自定义指令,把按钮所需要的权限写到表达式

//3.自定义指令内部,用当前按钮需要的权限和用户权限对比,如果没有就移除按钮 el.parenNode.removeChild(el)


let vHas = {
    mounted(el, binding) {
        // console.log(el)
        // console.log(binding)
        //判断binding.value(用户拥有的权限) 是否包含binding.arg('按钮需要的权限字段')
        //如果不包含 那么就直接移除当前按钮

        let has = binding.value.includes(binding.arg)

        // console.log(has)

        if (!has) {
            //如果没有权限 就移除节点
            el.parentNode.removeChild(el)
        }
    }
}

let stuDialogStore = useStuDialog()
// 声明属性
const list = ref([])
const searchInputValue = ref()

//展示搜索联想的结果
const options = ref([])

//搜索加载提示
const loading = ref(false)

//远程搜索的方法

let searchFn = async (key, count, page) => {
    //判断,如果key是空字符,那么就不搜索了
    if (!key) {
        options.value = [];
        return
    }
    //打开搜索加载提示
    loading.value = true;
    try {
        let res = await api.searchStuApi(key, count, page)
        //关闭搜索加载提示
        loading.value = false;
        // console.log(res)
        //给搜索联想的数组赋值
        options.value = res.data.data;
    } catch (e) {
        console.log(e)
    }
}

/**
 * 
 * @param {String} key 获取输入框输入的关键字
 */

let remoteMethod = (key) => {
    if (key) {
        lastKey.value = key
    }
    //发起请求 获取远程搜索结果
    searchFn(key)
}

//上一次搜索框输入值
let lastKey = ref()
//搜索,选中关键字的时候

let handleSelectSearchKey = async (val) => {
    //打开表格的加载动画

    tableLoading.value = true;

    //val是选中的关键字
    //再次发起搜索请求
    //清空搜索关键字,应该显示所有数据的第1页
    //搜索的时候,没有传关键字,默认返回所有的数据
    //需要的


    if (!val) {
        //1.展示第1页数据
        pageData.value.page = 1;
    }

    try {
        let res = await api.searchStuApi(val, pageData.value.count, pageData.value.page)
        // console.log(res)
        if (!val) {
            //2.分页器的total,也应该是根据所有的数据数量进行分页
            pageTotal.value = res.data.total;
            //3.分页器的选中页码变成第1页
            // console.log(val)
            currentPage.value = 1;
        }
        //赋值给表格
        stuTableData.value = res.data.data

        //关闭表格的加载动画
        tableLoading.value = false
    } catch (e) {
        console.log(e)
    }
}

//点击搜索按钮

let handleSearchButton = async () => {
    //打开表格的加载动画
    tableLoading.value = true;
    // console.log(lastKey.value)

    //1.声明一个lastKey用于存储在input里面的输入值

    //2.输入框的输入事件(remote-method)回调中,对lastKey赋值

    //3.点击按钮的时候,给selet v-model的变量赋值为lastKey
    searchInputValue.value = lastKey.value;

    //调用搜索逻辑

    try {
        let res = await api.searchStuApi(lastKey.value, pageData.value.count, pageData.value.page);
        stuTableData.value = res.data.data;
        //修改分页总数
        pageTotal.value = res.data.total;
        //关闭表格的加载动画
        tableLoading.value = false;
    } catch (e) {
        console.log(e)
    }
}


//表格加载动画
let tableLoading = ref(false)

//分页总数目

let pageTotal = ref(0)

//当期页码变量

let currentPage = ref(1)

//分页数据归纳

let pageData = ref({
    page: 1,
    count: 5,
    classes: ""
})

//分页器点击的时候处理函数

let handleSizeChange = (pageSize) => {

    //判断是否是搜索状态,如果是搜索状态,应该展示搜索结果的分页,而不是学员全部信息的分页

    //判断依据是 如果有搜索关键字,应该展示搜索的分页结果

    //如果没有 就展示所有学员信息的分页
    // console.log(searchInputValue.value)


    pageData.value.page = pageSize;

    if (searchInputValue.value) {
        handleSearchButton()
    } else {
        getStuList()
    }
}



//响应式的表格数据
const stuTableData = ref([])

//封装一个方法,专门用于请求表格数据

//声明一个变量,存储所有的图片地址,便于给Image组件进行预览

let srcList = ref([])

let getStuList = async (params = pageData.value) => {
    let { page, count, classes } = params;
    //打开加载动画
    tableLoading.value = true;
    //发起请求
    try {
        let res = await api.getStuListApi(page, count, classes)
        // console.log(res)
        stuTableData.value = res.data.data;

        srcList.value = stuTableData.value.map(item => item.headimgurl)
        // console.log(srcList)
        // console.log(stuTableData.value)
        //分页总数目
        pageTotal.value = res.data.total

        //关闭加载动画
        tableLoading.value = false;

    } catch (e) { }
}

getStuList()

//控制修改dialog的标题变量

let dialogTitle = ref('')

//增加学员信息
let actionType = ref('add')
let handleAddStu = () => {
    //显示dialog
    stuDialogStore.stuDialogVisible = true;
    //变更dialog标题
    dialogTitle.value = '增加学员信息'
    actionType.value = 'add'
}

//声明响应式变量传递给dialog组件

let reDisplayData = ref()

//点击编辑学员信息
let handleEditStu = (row, scope) => {
    console.log(row)
    //显示dialog
    stuDialogStore.stuDialogVisible = true;
    //变更dialog标题
    dialogTitle.value = '编辑学员信息'
    reDisplayData.value = { ...row }
    actionType.value = 'edit'
}

//删除学员信息

let handleDelete = row => {

    ElMessageBox({
        title: "删除提示",
        message: "该操作将永久删除本条数据,是否继续",
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        showCancelButton: true,
        icon: Warning,
    })
        .then(async () => {
            try {
                let res = await api.delStuApi(row.sId)
                ElMessage.success(res.data.msg)
                //更新列表
                getStuList()
            } catch (e) {
                console.log(e)
            }
        }).catch(() => {
            ElMessage.warning('已取消删除')
        })


}

//导出excel逻辑

//定义titleList

let titleList = [
    {
        title: '姓名',
        key: "name"
    },
    {
        title: '班级',
        key: 'class'
    },
    {
        title: '头像地址',
        key: 'headimgurl'
    },
    {
        title: '学历',
        key: 'degree'
    }
]

//再定义dataSource


let handleExportExcel = () => {
    try {
        qee(titleList, stuTableData.value, '学员数据')
        ElMessage.success('导出成功')
    } catch (e) {
        ElMessage.error('导出失败')
    }
}

</script>
<style lang="scss" scoped>
.search,
.table,
.add {
    margin: 40px;
}

.search {
    :deep(.el-input__wrapper) {
        min-width: 400px;
        height: 40px;
    }
}

.el-pagination {
    justify-content: center;
}

.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}

.el-input__wrapper {
    width: 300px;
}

</style>